﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using xNet;

namespace Clients
{
    public class HttpHelper
    { 
        /// <summary>
        /// 获取文本内容
        /// </summary>
        /// <param name="urlAddress">地址</param>
        /// <param name="proxyIP">代理IP</param> 
        public static bool Get(string urlAddress, string proxyIP, out string content)
        {
            content = string.Empty;
            try
            {
                using (var request = new HttpRequest())
                {
                    var proxyClient = HttpProxyClient.Parse(proxyIP);
                    request.UserAgent = Http.ChromeUserAgent();
                    request.Proxy = proxyClient;
                    HttpResponse response = request.Get(urlAddress);
                    content = response.ToString();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Logging4net.WriteError(ex);
                return false;
            } 
        }
          
        public static bool DownFile(string urlAddress, string localPath, string filename, string proxyIP)
        {
            if (false == System.IO.Directory.Exists(localPath))
            { 
                System.IO.Directory.CreateDirectory(localPath);  //创建pic文件夹
            }

            try
            {
                using (var request = new HttpRequest())
                {
                    var proxyClient = HttpProxyClient.Parse(proxyIP);
                    request.UserAgent = Http.ChromeUserAgent();
                    HttpResponse response = request.Get(urlAddress);
                    request.Proxy = proxyClient;
                    var content = response.ToBytes();

                    File.WriteAllBytes($"{localPath}\\{filename}", content);
                    return true;
                } 
            }
            catch (Exception ex)
            {
                Logging4net.WriteError(ex);
                return false;
            }
       
        } 
    }
}
